<template>
  <view class="coupon-list-content">


    <view class="data-state-content" v-if="isDisplay">
      <view class="state-icon">
        <uni-icons fontFamily="iconfont" :size="80" color="#91acc8">{{`&#xe60e;`}}</uni-icons>
        <text style="margin-top: 20rpx;">暂无优惠券</text>
      </view>
    </view>

    <view class="coupon-switch">
      <template v-for="(item,index) in typeList" :key="index">
        <text :class="[couponTypeItem,item.checked? couponTypeItemTrue:couponTypeItemFalse]"
          @click.stop="switchClick(item)">
          {{item.typeHint+" "+item.count}}
        </text>

      </template>
    </view>

    <view class="coupon-list-view">
      <template v-for="(item,index) in displayList" :key="index">
        <view class="coupon-list-item">
          <view class="item-top">

            <view class="item-top-center">
              <text class="center-description">{{item.hintName}}</text>
              <text>有效期 <text
                  class="date-value">{{`${item.coupon_batch.valided_at}-${item.coupon_batch.expired_at}`}}</text>
              </text>
            </view>
            <view class="item-top-right">
              <view class="right-item-state1">
                <text class="coupon-value" v-if="item.valueHint>0">{{displayPriceOrign(item.valueHint)}}</text>
                <text class="discount-value" v-if="item.discountValueHint.length>0">{{item.discountValueHint}}</text>
              </view>
              <text class="right-state-hint">{{item.limitHint}}</text>
            </view>
          </view>
          <view class="item-bottom">
            <uni-collapse>
              <custom-collapse-item title="使用说明" title-border="none">
                <view class="coupon-explain-value">
                  <text>{{item.coupon_batch.remark}}</text>
                </view>
              </custom-collapse-item>
            </uni-collapse>
            <view v-if="couponType == 1" class="click-use-coupon" @click="couponBtClick(item)">
              <text>点击领取</text>

            </view>
            <view v-else class="click-use-coupon" @click="toUse(item)">
              <text>去使用</text>

            </view>
          </view>*


        </view>
      </template>

    </view>
  </view>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { onReady, onLoad } from '@dcloudio/uni-app';
  import { getUserCoupons, queryUserAllCoupon, postGetCoupon } from "@/common/utils/requestModel.js"
  import { displayPriceOrign } from "@/common/utils/public.ts"
  import { DataInfo, CouponBean, Coupon, CouponBatch, CouponTicket } from '@/common/models/BaseData.ts'

  const typeList = ref([
    { type: 0, typeHint: "可用", count: 0, checked: false },
    { type: 1, typeHint: "领券中心", count: 0, checked: false }])
  const isDisplay = ref(true)
  const couponType = ref(0)

  onLoad(() => {

  })

  onReady(() => {
    console.log('onReady--')


    // switchClick(typeList.value[1])
    requestUserAllCoupons(typeList.value[0], false)
    requestUserCoupons(typeList.value[1])
  })

  function loadingShow(hint : string = "加载中") {
    uni.showLoading({
      title: hint
    })
  }
  function loadingHide(isSuccess : boolean = false) {
    if (!isSuccess) {
      uni.showToast({
        title: '加载失败',
        duration: 2000
      });
    }
    uni.hideLoading()

    // isSwitchClick.value = true
  }

  const isSwitchClick = ref(true)
  const currentSwitch = ref({})
  function switchClick(item) {
    console.log("分类:" + item.type)
    if (couponList.value.length > 0 || couponAllList.value.length > 0) {
      isDisplay.value = false
    }
    if (currentSwitch.value.type == item.type) {
      return
    }
    // if (!isSwitchClick.value) {
    // uni.showToast({
    //   title: '点击太快',
    //   duration: 2000
    // });
    // return
    // }
    currentSwitch.value = item
    // isSwitchClick.value = false
    for (let index in typeList.value) {
      let item = typeList.value[index]
      // item.count = 0
      item.checked = false
    }
    item.checked = true
    couponType.value = item.type
    if (item.type == 0) {
      // requestUserAllCoupons(item)
      item.count = couponAllList.value.length
      displayList.value = couponAllList.value
    } else {
      // requestUserCoupons(item)
      item.count = couponList.value.length
      displayList.value = couponList.value
    }
    // typeList.value = typeList.value
  }

  const couponTypeItem = "coupon-type-item"
  const couponTypeItemTrue = "coupon-type-item-true"
  const couponTypeItemFalse = "coupon-type-item-false"


  const displayList = ref<Array<CouponBean>>([])

  const couponList = ref<Array<CouponBean>>([])
  async function requestUserCoupons(item, isLoadMore : boolean = false) {
    // if (couponAllList.value.length > 0 && !isLoadMore) {
    //   couponType.value = 0
    //   displayList.value = couponAllList.value
    //   return
    // }

    loadingShow()
    let device = uni.getStorageSync(getApp().globalData.DEVICE_TAG)
    getUserCoupons(device.owner_id).then((result => {
      console.log("优惠券列表信息:", result)
      if (result.data.code != undefined) {
        loadingHide()
        return
      }
      let arr = new Array<CouponBean>()
      for (const item of result.data.items) {
        let coupon = new Coupon(
          item.coupon.coupon_batch_id,
          item.coupon.object_id,
          item.coupon.mode,
          item.coupon.threshold,
          item.coupon.reduce,
          item.coupon.discount,
          item.coupon.quantity,
          item.coupon.got,
          item.coupon.used
        )
        let coupon_batch = new CouponBatch(
          item.coupon_batch.operator_id,
          item.coupon_batch.coupon_type,
          item.coupon_batch.batch,
          item.coupon_batch.name,
          item.coupon_batch.quantity,
          item.coupon_batch.got,
          item.coupon_batch.used,
          item.coupon_batch.valided_at,
          item.coupon_batch.expired_at,
          item.coupon_batch.remark
        )

        arr.push(new CouponBean(coupon, coupon_batch))

      }

      item.count = arr.length
      couponList.value = arr
      switchClick(typeList.value[1])
      loadingHide(true)
    })).catch((e) => {
      loadingHide()
    })
  }

  const couponAllList = ref<Array<CouponBean>>([])
  async function requestUserAllCoupons(item, isAdd : boolean, isLoadMore : boolean = false) {
    // if (couponAllList.value.length > 0 && !isLoadMore) {
    //   couponType.value = 1
    //   displayList.value = couponAllList.value
    //   return
    // }
    loadingShow()
    let device = uni.getStorageSync(getApp().globalData.DEVICE_TAG)

    queryUserAllCoupon(device.owner_id, {}).then((result => {
      console.log("优惠券所有信息:", result)
      if (result.data.code == 'undefined') {
        loadingHide()
        return
      }

      let arr = new Array<CouponBean>()
      for (const item of result.data.items) {
        let coupon = new Coupon(
          item.coupon.coupon_batch_id,
          item.coupon.object_id,
          item.coupon.mode,
          item.coupon.threshold,
          item.coupon.reduce,
          item.coupon.discount,
          item.coupon.quantity,
          item.coupon.got,
          item.coupon.used
        )
        let coupon_batch = new CouponBatch(
          item.coupon_batch.operator_id,
          item.coupon_batch.coupon_type,
          item.coupon_batch.batch,
          item.coupon_batch.name,
          item.coupon_batch.quantity,
          item.coupon_batch.got,
          item.coupon_batch.used,
          item.coupon_batch.valided_at,
          item.coupon_batch.expired_at,
          item.coupon_batch.remark
        )
        let coupon_ticket = new CouponTicket(
          item.coupon_ticket.code,
          item.coupon_ticket.coupon_id,
          item.coupon_ticket.created_at,
          item.coupon_ticket.deleted,
          item.coupon_ticket.device_id,
          item.coupon_ticket.object_id,
          item.coupon_ticket.order_id,
          item.coupon_ticket.updated_at,
          item.coupon_ticket.user_id
        )
        arr.push(new CouponBean(coupon, coupon_batch, coupon_ticket))

      }

      item.count = arr.length
      couponAllList.value = arr
      item.count = couponAllList.value.length
      if (isAdd) {
        switchClick(typeList.value[0])
      }
      loadingHide(true)
    })).catch((e) => {
      loadingHide()
    })
  }

  function toUse(item) {
    uni.reLaunch({
      url: '../pages/index/index'
    });
  }

  function couponBtClick(item) {
    console.log("点击按钮")
    if (couponType.value == 0) {
      receiveCoupon(item.coupon.object_id)
    } else {
    }
  }

  function receiveCoupon(couponId : string) {
    loadingShow("领取中")
    postGetCoupon(couponId).then((result => {
      console.log("领取优惠券:", result)
      if (result.data.code == 'undefined') {
        loadingHide()
        return
      }

      loadingHide(true)

      requestUserAllCoupons(typeList.value[0], true)
    })).catch((e) => {
      loadingHide()
    })
  }
</script>

<style lang="scss">
  .coupon-list-content {
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100%;
    height: 100%;
    padding: 20rpx;
    box-sizing: border-box;
    background: #dadada;
    // background:red;
  }

  .coupon-switch {
    display: inline-flex;
    width: 100%;
    height: 80rpx;
    background: #FEEB64;
    padding: 6rpx;
    box-sizing: border-box;
    border-radius: 50rpx;

    .coupon-type-item {
      width: 50%;
      height: 100%;
      line-height: 72rpx;
      text-align: center;
    }

    .coupon-type-item-true {
      border-radius: 50rpx;
      background: $color-white;
    }

    .coupon-type-item-false {}

  }

  .data-state-content {
    position: absolute;
    width: 100%;
    height: 100%;
    // background: blue;
    pointer-events: none; //允许事件穿透

    .state-icon {
      position: absolute;
      top: 30%;
      left: 50%;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      transform: translateX(-50%);
      font-weight: 700;
    }
  }

  .coupon-list-view {
    width: 100%;
    height: 90%;
    box-sizing: border-box;

    .coupon-list-item {
      width: 100%;
      height: 300rpx;
      margin-top: 20rpx;
      padding: 20rpx 0;
      box-sizing: border-box;
      border-radius: 20rpx;
      background: $color-white;

      .item-top {
        display: inline-flex;
        width: 100%;
        height: 65%;
        padding: 0 20rpx;
        background: $color-white;
        border-bottom: 1px dotted #D8D8D8;
        box-sizing: border-box;



        .item-top-center {
          display: flex;
          flex-direction: column;
          justify-content: center;
          width: 75%;
          height: 100%;

          .center-description {
            padding: 10rpx 0;
            font-size: 35rpx;
            font-weight: 700;
            color: red;
          }

          text:nth-child(2) {
            padding: 10rpx 0;
            font-size: 25rpx;
            color: #bdbdbd;

            .date-value {
              margin-left: 10rpx;
              color: #bdbdbd;
            }
          }
        }

        .item-top-right {
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          width: 25%;
          height: 100%;

          .right-item-state1 {
            display: inline-flex;
            justify-content: center;
            align-items: baseline;
            width: 100%;
            text-align: center;
            color: red;

            .coupon-value {
              font-size: 60rpx;
              font-weight: 700;
            }

            .coupon-value::first-letter {
              font-size: 50%;
              /* 将第一个字母的字体大小设为原来的50% */
            }

            .discount-value {
              font-size: 24px;
              display: inline-block;
              position: relative;
            }

            .discount-value::after {
              content: "2";
              position: absolute;
              top: 0;
              left: 100%;
              /* 使伪元素出现在主内容之后 */
              transform: scale(0.7) translateX(-50%);
              /* 缩小并调整位置 */
              transform-origin: left;
              /* 调整缩放的基点 */
            }
          }

          .right-state-hint {
            color: red;
            font-size: 25rpx;
          }
        }

      }

      .item-bottom {
        position: relative;
        width: 100%;
        height: 35%;
        padding: 10rpx 0;
        background: $color-white;

        .coupon-explain-value {
          width: 100%;
          padding: 10rpx 30rpx;
          box-sizing: border-box;
          text-align: left;
        }

        .click-use-coupon {
          position: absolute;
          right: 20rpx;
          top: 50%;
          width: 150rpx;
          height: 60%;
          text-align: center;
          line-height: 65rpx;
          border-radius: 10rpx;
          background: linear-gradient(270deg, #FF4755 0%, #FF6D15 100%);
          transform: translateY(-50%);
          color: white;
          font-size: 30rpx;
        }
      }

    }
  }
</style>